# Create your views here.

import json
from re import S, T
from traceback import print_exc
import django

from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from app.FileTypeEnum import FileTypeEnum, FolderStatusEnum
from app.filesUtils import *

from app.graph_templates import GraphTemplate
from app.graphsUtils import copy_project_graphs
from app.jumpLinkEnum import *
from app.modelUtils import isValidEmail
from app.utils import *
from app.models import *
from app.statusenum import *


@csrf_exempt
def login_test_view(request):
    token = create_file_token("test")
    print(token)
    print(decode_file_token(token))
    return JsonResponse({"data": create_token("test")})


@csrf_exempt
def logined_test_view(request):
    try:
        token = request.META.get('HTTP_AUTHORIZATION')
        payload = validate_token(token)
        if payload:
            return JsonResponse(payload)
        else:
            return JsonResponse({"error": "invalid token"})
    except Exception as e:
        return JsonResponse({"error": str(e)})


@csrf_exempt
def login(request):
    if request.method == 'POST':
        identity = request.POST.get('identity')
        password = request.POST.get('password')
        loginmethod = request.POST.get('loginmethod')
        if identity and password and loginmethod:
            try:
                if loginmethod == 'email':
                    user = Users.objects.get(email=identity)
                elif loginmethod == 'user_name':
                    user = Users.objects.get(user_name=identity)
                else:
                    return JsonResponse({"errno": 2005, "msg": "登录方式错误"})

                if user.pass_word == password:
                    token = create_token(user.user_id, TokenTypeEnum.LOGIN_TOKEN.value)
                    return JsonResponse({"errno": 0, "msg": "成功", "data": {"token": token, "user_id": user.user_id,
                                                                           "user_name": user.user_name,
                                                                           "profile": user.profile}})
                else:
                    return JsonResponse({"errno": 2001, "msg": "密码错误"})
            except Users.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "用户不存在"})
        else:
            return JsonResponse({"errno": 2003, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2004, "msg": "请求方式错误"})


@csrf_exempt
def get_logined_userinfo(request):
    if request.method == 'GET':
        try:
            payload = getTokenPayloadOfRequest(request)
            if payload is None:
                return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
            user_id = payload['payload']
            # 验证用户是否激活
            user = Users.objects.get(user_id=user_id)
            if user.user_status == UserStatusEnum.INACTIVE.value:
                return JsonResponse({"errno": 1001, "msg": "用户未激活"})

            user = Users.objects.get(user_id=user_id)
            return JsonResponse({"errno": 0, "msg": "成功",
                                 "data": {"user_id": user.user_id, "user_name": user.user_name, "email": user.email,
                                          "real_name": user.real_name, "user_status": user.user_status,
                                          "user_info": user.user_info, "profile": user.profile}})
        except Exception as e:
            return JsonResponse({"error": str(e)})
    else:
        return JsonResponse({"errno": 2004, "msg": "请求方式错误"})


@csrf_exempt
def send_email_test(request):
    # 先这么写着
    email = request.POST.get('email')
    send_type = request.POST.get('send_type')
    status = send_verification_code(email, send_type)
    return JsonResponse({"send_email_status": status})


@csrf_exempt
def register(request):
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        pass_word = request.POST.get('pass_word')
        email = request.POST.get('email')
        real_name = request.POST.get('real_name')
        code = request.POST.get('code')
        if user_name and pass_word and email and real_name and code:
            # 判断用户名是否存在
            try:
                user = Users.objects.get(user_name=user_name)
                return JsonResponse({"errno": 2001, "msg": "用户名已存在"})
            except Users.DoesNotExist:
                pass
            # 判断邮箱是否存在
            try:
                user = Users.objects.get(email=email)
                return JsonResponse({"errno": 2002, "msg": "邮箱已存在"})
            except Users.DoesNotExist:
                pass
            # 判断邮箱是否合法
            if not isValidEmail(email):
                return JsonResponse({"errno": 2003, "msg": "邮箱不合法"})
            # 判断验证码是否正确
            try:
                temp_email = Emails.objects.get(email_address=email)
                if int(code) != temp_email.verification_code:
                    return JsonResponse({"errno": 2004, "msg": "验证码错误"})
            except Emails.DoesNotExist:
                return JsonResponse({"errno": 2005, "msg": "未发送验证码"})
            # 创建用户
            user = Users(user_name=user_name, pass_word=pass_word, email=email, real_name=real_name,
                         user_status=UserStatusEnum.NORMAL.value, user_info="这个家伙很懒，什么也没有留下",
                         real_name_update_time=django.utils.timezone.now())
            user.save()
            # 获取user_id
            user_id = user.user_id
            return JsonResponse({"errno": 0, "msg": "注册成功", "data": {"user_id": user_id}})
        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def active(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        user_id = payload['payload']
        token = request.POST.get('token')
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "payload不合法"})
        else:
            pass
        if not token:
            return JsonResponse({"errno": 2002, "msg": "无效的token"})
        else:
            pass
        # @csrf_exempt
        # def activate(request):
        #     if request.method == 'POST':
        #         token = request.POST.get('token')
        #         if not token:
        #             return JsonResponse({"errno": 2001, "msg": "请求参数存在空值"})
        #         else:
        #             pass
        #         payload = validate_token(token)
        #         if payload is None:
        #             return JsonResponse({"errno": 2002, "msg": "token不合法"})
        #         user_id = payload['payload']

        user = Users.objects.get(user_id=user_id)
        if not user:
            JsonResponse({"errno": 2003, "msg": "用户不存在"})
        else:
            pass
        try:
            user.user_status = UserStatusEnum.NORMAL
            user.save()
        except Exception as e:
            print(str(e))
            return JsonResponse({"errno": 2004, "msg": "激活失败"})
        return JsonResponse({"errno": 0, "msg": "激活成功"})
    else:
        return JsonResponse({"errno": 2005, "msg": "请求方式错误"})


@csrf_exempt
def search_user_by_username(request):
    # 模糊查询：返回查询到的用户信息的前20条（排序依据长度最短+字典序，完全包含）
    # 精确查询：用户信息完全匹配
    if request.method == 'POST':
        user_name = request.POST.get('user_name')
        query_type = request.POST.get('query_type')
        if user_name and query_type:
            if query_type == 'fuzzy':
                users = Users.objects.filter(user_name__contains=user_name)
                # 排序users内容 长度最短+字典序
                users = sorted(users, key=lambda x: (len(x.user_name), x.user_name))
                users = users[:20]
                user_list = []
                for user in users:
                    # 'real_name': user.real_name 属于非公开信息
                    user_list.append({'user_id': user.user_id, 'user_name': user.user_name, "email": user.email,
                                      'user_status': user.user_status, 'user_info': user.user_info,
                                      "profile": user.profile})
                return JsonResponse({"errno": 0, "msg": "查询成功", "data": {"user_list": user_list}})
            elif query_type == 'exact':
                try:
                    user = Users.objects.get(user_name=user_name)
                    exactuser = {'user_id': user.user_id, 'user_name': user.user_name, "email": user.email,
                                 'user_status': user.user_status, 'user_info': user.user_info, "profile": user.profile}
                    return JsonResponse({"errno": 0, "msg": "查询成功", "data": {"user": exactuser}})
                except Users.DoesNotExist:
                    return JsonResponse({"errno": 2006, "msg": "用户不存在"})
            else:
                return JsonResponse({"errno": 2007, "msg": "未知错误：查询类型错误"})

        else:
            return JsonResponse({"errno": 2008, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2009, "msg": "请求方式错误"})


@csrf_exempt
def search_team_by_teamname(request):
    # 精确查询：团队名称完全匹配的所有结果
    # 模糊查询：团队名称完全匹配结果 + 不完全匹配但完全包含的信息的前20条（排序依据长度最短+字典序，完全包含）
    if request.method == 'POST':
        team_name = request.POST.get('team_name')
        query_type = request.POST.get('query_type')
        all_query_type = ['fuzzy', 'exact']

        if team_name and query_type:
            if query_type not in all_query_type:
                return JsonResponse({"errno": 2007, "msg": "未知错误：查询类型错误"})

            teams = Teams.objects.filter(team_name=team_name)
            team_exact_list = []
            for team in teams:
                # 获取团队成员数量
                team_member_list = Teams2Users.objects.filter(team_id=team.team_id)
                team_member_num = len(team_member_list)
                # 获取项目下identitys为OWNER的唯一成员
                team_owner_user = Users.objects.get(user_id=team.team_owner_user_id)
                team_exact_list.append({'team_id': team.team_id, 'team_name': team.team_name,
                                        "team_type": team.team_type, "team_info": team.team_info,
                                        "team_time": team.team_time,
                                        "team_owner_user_id": team.team_owner_user_id,
                                        "team_owner_user_name": team_owner_user.user_name,
                                        "team_owner_user_email": team_owner_user.email,
                                        'team_owner_user_info': team_owner_user.user_info,
                                        "team_member_num": team_member_num})
            if query_type == 'exact':
                return JsonResponse({"errno": 0, "msg": "查询成功", "data": {"team_exact_list": team_exact_list}})

            teamsappend = Teams.objects.filter(team_name__contains=team_name).exclude(team_name=team_name)
            # 排序teamsappend内容 长度最短+字典序
            appendnum = max(20 - len(teams), 10)
            teamsappend = sorted(teamsappend, key=lambda x: (len(x.team_name), x.team_name))
            teamsappend = teamsappend[:appendnum]
            team_fuzzy_list = []
            for team in teamsappend:
                # 获取团队成员数量
                team_member_list = Teams2Users.objects.filter(team_id=team.team_id)
                team_member_num = len(team_member_list)
                # 获取项目下identitys为OWNER的唯一成员
                team_owner_user = Users.objects.get(user_id=team.team_owner_user_id)
                team_fuzzy_list.append({'team_id': team.team_id, 'team_name': team.team_name,
                                        "team_type": team.team_type, "team_info": team.team_info,
                                        "team_time": team.team_time,
                                        "team_owner_user_id": team.team_owner_user_id,
                                        "team_owner_user_name": team_owner_user.user_name,
                                        "team_owner_user_email": team_owner_user.email,
                                        'team_owner_user_info': team_owner_user.user_info,
                                        "team_member_num": team_member_num})

            return JsonResponse({"errno": 0, "msg": "查询成功",
                                 "data": {"team_fuzzy_list": team_fuzzy_list, "team_exact_list": team_exact_list}})

        else:
            return JsonResponse({"errno": 2008, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2009, "msg": "请求方式错误"})


@csrf_exempt
def create_team(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        team_name = request.POST.get('team_name')
        team_type = request.POST.get('team_type')
        team_info = request.POST.get('team_info')

        if team_name and team_type and team_info:
            team = Teams(team_name=team_name, team_type=team_type, team_info=team_info,
                         team_time=django.utils.timezone.now(), team_owner_user_id=user_id)
            team.save()
            teamtouser = Teams2Users(user_id=user_id, team_id=team.team_id, identitys=TeamIdentityEnum.OWNER.value)
            teamtouser.save()
            # 创建files model
            files = Files(parent_id=0,
                          folder_name=None,
                          file_type=FileTypeEnum.TEAM_ROOT.value,
                          content_id=team.team_id,
                          team_id=team.team_id,
                          )
            files.save()

            return JsonResponse({"errno": 0, "msg": "创建成功", "data": {"team_id": team.team_id}})
        else:
            return JsonResponse({"errno": 2002, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2003, "msg": "请求方式错误"})


@csrf_exempt
def get_team_list(request):
    if request.method == 'GET':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        try:
            team_list_owner = Teams2Users.objects.filter(user_id=user_id, identitys=TeamIdentityEnum.OWNER.value)
        except Teams2Users.DoesNotExist:
            team_list_owner = []
            pass
        try:
            team_list_admin = Teams2Users.objects.filter(user_id=user_id, identitys=TeamIdentityEnum.ADMIN.value)
        except Teams2Users.DoesNotExist:
            team_list_admin = []
            pass
        try:
            team_list_member = Teams2Users.objects.filter(user_id=user_id, identitys=TeamIdentityEnum.MEMBER.value)
        except Teams2Users.DoesNotExist:
            team_list_member = []
            pass
        try:
            data = {}
            team_list_owner_json = []
            for team2user in team_list_owner:
                # 获取团队成员数量
                team = Teams.objects.get(team_id=team2user.team_id)
                team_member_list = Teams2Users.objects.filter(team_id=team.team_id)
                team_member_num = len(team_member_list)
                # 获取项目下identitys为OWNER的唯一成员

                team_owner_user = Users.objects.get(user_id=team.team_owner_user_id)
                team_list_owner_json.append({'team_id': team.team_id, 'team_name': team.team_name,
                                             "team_type": team.team_type, "team_info": team.team_info,
                                             "team_time": team.team_time,
                                             "team_owner_user_id": team.team_owner_user_id,
                                             "team_owner_user_name": team_owner_user.user_name,
                                             "team_owner_user_email": team_owner_user.email,
                                             'team_owner_user_info': team_owner_user.user_info,
                                             "team_member_num": team_member_num})
            data['team_list_owner'] = team_list_owner_json

            team_list_admin_json = []
            for team2user in team_list_admin:
                # 获取团队成员数量
                team = Teams.objects.get(team_id=team2user.team_id)
                team_member_list = Teams2Users.objects.filter(team_id=team.team_id)
                team_member_num = len(team_member_list)
                # 获取项目下identitys为OWNER的唯一成员

                team_owner_user = Users.objects.get(user_id=team.team_owner_user_id)
                team_list_admin_json.append({'team_id': team.team_id, 'team_name': team.team_name,
                                             "team_type": team.team_type, "team_info": team.team_info,
                                             "team_time": team.team_time,
                                             "team_owner_user_id": team.team_owner_user_id,
                                             "team_owner_user_name": team_owner_user.user_name,
                                             "team_owner_user_email": team_owner_user.email,
                                             'team_owner_user_info': team_owner_user.user_info,
                                             "team_member_num": team_member_num})
            data['team_list_admin'] = team_list_admin_json

            team_list_member_json = []
            for team2user in team_list_member:
                # 获取团队成员数量
                team = Teams.objects.get(team_id=team2user.team_id)
                team_member_list = Teams2Users.objects.filter(team_id=team.team_id)
                team_member_num = len(team_member_list)
                # 获取项目下identitys为OWNER的唯一成员

                team_owner_user = Users.objects.get(user_id=team.team_owner_user_id)
                team_list_member_json.append({'team_id': team.team_id, 'team_name': team.team_name,
                                              "team_type": team.team_type, "team_info": team.team_info,
                                              "team_time": team.team_time,
                                              "team_owner_user_id": team.team_owner_user_id,
                                              "team_owner_user_name": team_owner_user.user_name,
                                              "team_owner_user_email": team_owner_user.email,
                                              'team_owner_user_info': team_owner_user.user_info,
                                              "team_member_num": team_member_num})

            data['team_list_member'] = team_list_member_json
            return JsonResponse({"errno": 0, "msg": "获取成功", "data": data})
        except Teams.DoesNotExist:
            return JsonResponse({"errno": 2004, "msg": "未知错误"})
    else:
        return JsonResponse({"errno": 2003, "msg": "请求方式错误"})


@csrf_exempt
def del_team(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        if team_id:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})
            if teamtouser.identitys >= TeamIdentityEnum.OWNER.value:
                # 移除团队所有成员
                Teams2Users.objects.filter(team_id=team_id).delete()
                # 移除团队
                team.delete()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            else:
                return JsonResponse({"errno": 2004, "msg": "您不是该团队拥有者"})
        else:
            return JsonResponse({"errno": 2005, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2006, "msg": "请求方式错误"})


@csrf_exempt
def rename_team(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        team_name = request.POST.get('team_name')
        if team_id and team_name:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})
            if teamtouser.identitys >= TeamIdentityEnum.OWNER.value:
                team.team_name = team_name
                team.save()
                return JsonResponse({"errno": 0, "msg": "修改成功"})
            else:
                return JsonResponse({"errno": 2004, "msg": "您不是该团队拥有者"})
        else:
            return JsonResponse({"errno": 2005, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2006, "msg": "请求方式错误"})


@csrf_exempt
def generate_invite_link(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        invite_method = request.POST.get('invite_method')
        targeted = request.POST.get('targeted')
        invite_user_name = request.POST.get('invite_user_name')  # 被邀请人用户名

        invite_user = None
        if team_id:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})

            if teamtouser.identitys >= TeamIdentityEnum.ADMIN.value:
                if targeted:
                    if not invite_user_name:
                        return JsonResponse({"errno": 2009, "msg": "定向邀请时，被邀请人用户名不能为空"})
                    try:
                        invite_user = Users.objects.get(user_name=invite_user_name)  # 被邀请用户
                    except Users.DoesNotExist:
                        return JsonResponse({"errno": 2004, "msg": "用户不存在"})
                    if Teams2Users.objects.filter(team_id=team_id, user_id=invite_user.user_id):
                        return JsonResponse({"errno": 2010, "msg": "用户已经在团队中"})
                    invite_payload = {"team_id": team_id, "inviter_user_id": user_id, "targeted": True,
                                      "target_user_id": invite_user.user_id}
                else:
                    invite_payload = {"team_id": team_id, "inviter_user_id": user_id}
                token = create_token(invite_payload, TokenTypeEnum.INVITE_TOKEN.value)
                invite_link = JumpLink.INVITE_TO_TEAM.value + token
                if invite_method == 'email':
                    if not invite_user:
                        invite_user = Users.objects.get(user_name=invite_user_name)  # 被邀请用户
                    send_status = send_verification_code(invite_user.email, '2', invite_link, team_name=team.team_name,
                                                         user_name=invite_user_name)
                    if send_status == EmailSendStatusEnum.FAIL.value:
                        return JsonResponse({"errno": 2005, "msg": "邮件发送失败"})
                # 默认返回邀请链接(前端按需处理)
                return JsonResponse({"errno": 0, "msg": "邀请链接生成成功", "data": {"invite_link": invite_link}})
            else:
                return JsonResponse({"errno": 2006, "msg": "您不是该团队管理员"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def join_team_by_token(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        token = request.POST.get('token')
        # 验证token
        if not token:
            return JsonResponse({"errno": 2002, "msg": "请求参数存在空值"})
        else:
            pass
        # 解析token
        invite_payload = validate_token(token, TokenTypeEnum.INVITE_TOKEN.value)

        if invite_payload is None:
            return JsonResponse({"errno": 2003, "msg": "邀请链接错误"})

        invite_payload = invite_payload['payload']

        # 验证邀请者权限
        team_id = invite_payload['team_id']
        inviter_user_id = invite_payload['inviter_user_id']
        # 验证是否为定向邀请 以及验证受邀者
        if invite_payload.get('targeted', False):
            target_user_id = invite_payload['target_user_id']
            if target_user_id != user_id:
                return JsonResponse({"errno": 2004, "msg": "您不是该定向邀请链接的受邀人"})

        try:
            team = Teams.objects.get(team_id=team_id)
        except Teams.DoesNotExist:
            return JsonResponse({"errno": 2004, "msg": "团队不存在"})
        try:
            teamtouser = Teams2Users.objects.get(user_id=inviter_user_id, team_id=team_id)
        except Teams2Users.DoesNotExist:
            return JsonResponse({"errno": 2005, "msg": "邀请者不是该团队成员"})
        if teamtouser.identitys >= TeamIdentityEnum.ADMIN.value:
            try:
                teamtouser2 = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                teamtouser2 = Teams2Users(user_id=user_id, team_id=team_id, identitys=TeamIdentityEnum.MEMBER.value)
                teamtouser2.save()
                return JsonResponse({"errno": 0, "msg": "加入团队成功"})
            else:
                return JsonResponse({"errno": 2006, "msg": "该用户已是该团队成员"})
        else:
            return JsonResponse({"errno": 2007, "msg": "邀请者不是该团队管理员"})

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def send_code(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        send_type = request.POST.get('send_type')
        # 判断邮箱是否存在
        try:
            user = Users.objects.get(email=email)
            return JsonResponse({"errno": 2001, "msg": "邮箱已存在"})
        except Users.DoesNotExist:
            pass
        # 判断邮箱是否合法
        if not isValidEmail(email):
            return JsonResponse({"errno": 2002, "msg": "邮箱不合法"})

        send_status = send_verification_code(email, send_type)
        if send_status == EmailSendStatusEnum.FAIL.value:
            return JsonResponse({"errno": 2003, "msg": "发送失败"})
        return JsonResponse({"errno": 0, "msg": "发送成功"})
    else:
        return JsonResponse({"errno": 2004, "msg": "请求方式错误"})


@csrf_exempt
def del_team_member(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        user_id_to_del = request.POST.get('user_id_to_del')

        # 退出团队不应使用该接口 team_id和user_id_to_del不应相同
        if team_id == user_id_to_del:
            return JsonResponse({"errno": 2008, "msg": "不应使用移除成员的方法退出团队"})
        if team_id and user_id_to_del:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})

            try:
                teamtouser2 = Teams2Users.objects.get(user_id=user_id_to_del, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "对方不是该团队成员"})
            if teamtouser.identitys > teamtouser2.identitys:
                teamtouser2.delete()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            else:
                return JsonResponse({"errno": 2005, "msg": "您没有删除该成员的权限"})
        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def change_team_member_identitys(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        user_id_to_change = request.POST.get('user_id_to_change')
        identitys = request.POST.get('identitys')
        # 不应使用该接口变更自己的权限 team_id和user_id_to_change不应相同 
        # 自己的权限一定不高于自己 因此注释内容不使用
        # if team_id == user_id_to_change:
        #     return JsonResponse({"errno": -1, "msg": "自己不能变更自己的权限"})

        # 验证参数 identitys 是否合法
        if identitys == "admin":
            identitys = TeamIdentityEnum.ADMIN.value
        elif identitys == "member":
            identitys = TeamIdentityEnum.MEMBER.value
        else:
            identitys = None

        if team_id and user_id_to_change and identitys:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})
            try:
                teamtouser2 = Teams2Users.objects.get(user_id=user_id_to_change, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "对方不是该团队成员"})
            if teamtouser.identitys > teamtouser2.identitys and teamtouser.identitys > identitys:
                teamtouser2.identitys = identitys
                teamtouser2.save()
                return JsonResponse({"errno": 0, "msg": "修改成功"})
            else:
                return JsonResponse({"errno": 2005, "msg": "您没有授予该等级权限的权限"})
        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def get_team_member_list(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        if team_id:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})
            alluserlist = Teams2Users.objects.filter(team_id=team_id)
            team_member_list = []
            for team_member in alluserlist:
                user = Users.objects.get(user_id=team_member.user_id)
                team_member_list.append(
                    {"user_id": user.user_id, "user_name": user.user_name, "real_name": user.real_name,
                     "email": user.email, "identitys": team_member.identitys, "profile": user.profile})
            # 对team_member_list排序 以identitys降序排列
            team_member_list.sort(key=lambda x: x['identitys'], reverse=True)
            return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"team_member_list": team_member_list}})
        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def create_project(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        project_name = request.POST.get('project_name')

        if team_id and project_name:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})

            project = Projects(project_name=project_name, team_id=team_id,
                               project_status=ProjectStatusEnum.NORMAL.value,
                               create_time=django.utils.timezone.now(), update_time=django.utils.timezone.now())
            project.save()
            # 创建files model
            # 获得files model 的 TEAM_ROOT
            try:
                teamroot = Files.objects.get(team_id=team.team_id, file_type=FileTypeEnum.TEAM_ROOT.value)
            except Files.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "未知错误：团队根目录不存在"})
            files = Files(parent_id=teamroot.file_id,
                          folder_name=None,
                          file_type=FileTypeEnum.PROJECT.value,
                          content_id=project.project_id,
                          team_id=team.team_id,
                          )
            files.save()

            return JsonResponse({"errno": 0, "msg": "创建成功", "data": {"project_id": project.project_id}})

        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def get_project_list(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        project_name = request.POST.get('project_name')
        if team_id:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})
            if project_name:
                allprojectlist = Projects.objects.filter(team_id=team_id, project_name__contains=project_name)
            else:
                allprojectlist = Projects.objects.filter(team_id=team_id)
            project_normal_list = []
            project_recycle_list = []
            for project in allprojectlist:
                if project.project_status == ProjectStatusEnum.NORMAL.value:
                    # 获取项目的项目文件
                    try:
                        project_file = Files.objects.get(team_id=team.team_id, file_type=FileTypeEnum.PROJECT.value,
                                                         content_id=project.project_id)
                    except Files.DoesNotExist:
                        return JsonResponse({"errno": 2004, "msg": "未知错误：找不到项目根目录"})

                    project_normal_list.append({"project_id": project.project_id, "project_name": project.project_name,
                                                "create_time": project.create_time,
                                                "update_time": project.update_time,
                                                "project_status": project.project_status,
                                                "project_file_id": project_file.file_id,
                                                "team_name": team.team_name})
                elif project.project_status == ProjectStatusEnum.RECYCLE.value:
                    try:
                        project_file = Files.objects.get(team_id=team.team_id, file_type=FileTypeEnum.PROJECT.value,
                                                         content_id=project.project_id)
                    except Files.DoesNotExist:
                        return JsonResponse({"errno": 2004, "msg": "未知错误：找不到项目根目录"})
                    project_recycle_list.append({"project_id": project.project_id, "project_name": project.project_name,
                                                 "create_time": project.create_time,
                                                 "update_time": project.update_time,
                                                 "project_status": project.project_status,
                                                 "project_file_id": project_file.file_id,
                                                 "team_name": team.team_name})

            return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"project_normal_list": project_normal_list,
                                                                     "project_recycle_list": project_recycle_list}})
        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def get_project_fileid(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        project_id = request.POST.get('project_id')
        if not project_id:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
        try:
            project_file = Files.objects.get(file_type=FileTypeEnum.PROJECT.value, content_id=project_id)
        except Files.DoesNotExist:
            return JsonResponse({"errno": 2004, "msg": "找不到项目目录"})
        except Files.MultipleObjectsReturned:
            return JsonResponse({"errno": 2005, "msg": "未知错误：多个对应的项目目录"})
        ret = check_file_privelige(project_file, user_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

        return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"file_id": project_file.file_id}})

    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def rename_project(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        project_id = request.POST.get('project_id')
        project_name = request.POST.get('project_name')
        if project_id and project_name:
            project = Projects.objects.get(project_id=project_id)
            project.project_name = project_name
            project.save()
            return JsonResponse({"errno": 0, "msg": "重命名成功"})
        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def del_project(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        project_id = request.POST.get('project_id')
        if project_id:
            try:
                project = Projects.objects.get(project_id=project_id)
            except Projects.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "项目不存在"})
            # 验证用户是否是该项目所属的团队的成员
            try:
                team = Teams.objects.get(team_id=project.team_id)
            except Teams.DoesNotExist:
                # return JsonResponse({"errno": 2009, "msg": "未知错误"})
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=project.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

            if project.project_status == ProjectStatusEnum.NORMAL.value:
                project.project_status = ProjectStatusEnum.RECYCLE.value
                project.update_time = django.utils.timezone.now()
                project.save()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            elif project.project_status == ProjectStatusEnum.RECYCLE.value:
                return JsonResponse({"errno": 2005, "msg": "项目已加入回收站"})
            else:
                return JsonResponse({"errno": 2006, "msg": "未知错误：项目状态错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def permanent_del_project(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        project_id = request.POST.get('project_id')
        if project_id:
            try:
                project = Projects.objects.get(project_id=project_id)
            except Projects.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "项目不存在"})
            # 验证用户是否是该项目所属的团队的成员
            try:
                team = Teams.objects.get(team_id=project.team_id)
            except Teams.DoesNotExist:
                # return JsonResponse({"errno": 2010, "msg": "未知错误"})
                return JsonResponse({"errno": 2010, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=project.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2011, "msg": "您不是该团队成员"})

            if project.project_status == ProjectStatusEnum.NORMAL.value:
                return JsonResponse({"errno": 2005, "msg": "未知错误：项目不在回收站"})
            elif project.project_status == ProjectStatusEnum.RECYCLE.value:
                project.project_status = ProjectStatusEnum.DELETE.value
                project.update_time = django.utils.timezone.now()
                project.save()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            elif project.project_status == ProjectStatusEnum.DELETE.value:
                return JsonResponse({"errno": 2006, "msg": "项目已删除"})
            else:
                return JsonResponse({"errno": 2007, "msg": "未知错误：项目状态错误"})
        else:
            return JsonResponse({"errno": 2008, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2009, "msg": "请求方式错误"})


@csrf_exempt
def recycle_project(request):
    # 将项目状态由删除状态回收为正常状态
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        project_id = request.POST.get('project_id')
        if project_id:
            try:
                project = Projects.objects.get(project_id=project_id)
            except Projects.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "项目不存在"})
            # 验证用户是否是该项目所属的团队的成员
            try:
                team = Teams.objects.get(team_id=project.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=project.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

            if project.project_status == ProjectStatusEnum.RECYCLE.value:
                project.project_status = ProjectStatusEnum.NORMAL.value
                project.update_time = django.utils.timezone.now()
                project.save()
                return JsonResponse({"errno": 0, "msg": "恢复成功"})
            elif project.project_status == ProjectStatusEnum.NORMAL.value:
                return JsonResponse({"errno": 2005, "msg": "项目已恢复"})
            else:
                return JsonResponse({"errno": 2006, "msg": "未知错误：项目状态错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_doc_edit_time(request):
    # 更新文档的最后编辑时间
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        file_id = request.POST.get('file_id')
        if file_id:
            # 获取文件
            try:
                file = Files.objects.get(file_id=file_id)
            except Files.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档文件不存在"})
            # 获取文档
            try:
                doc = Documents.objects.get(doc_id=file.content_id)
            except Documents.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档不存在"})

            try:
                team = Teams.objects.get(team_id=file.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=file.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})
            if doc.doc_status == DocStatusEnum.NORMAL.value:
                doc.update_time = django.utils.timezone.now()
                doc.save()
                return JsonResponse({"errno": 0, "msg": "修改成功"})
            elif doc.doc_status == DocStatusEnum.RECYCLE.value:
                return JsonResponse({"errno": 2011, "msg": "文档已删除"})
            else:
                return JsonResponse({"errno": 2012, "msg": "未知错误：文档状态错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def create_doc(request):
    # 创建文档
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        create_method = request.POST.get('create_method')
        # if create_method == DocCreateMethodEnum.PROJECT_ID.value:
        #     已不受支持
        if create_method == DocCreateMethodEnum.FOLDER_ID.value:
            folder_id = request.POST.get('folder_id')
            if not folder_id:
                return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
        else:
            return JsonResponse({"errno": 2009, "msg": "无法解析的创建方式"})
        doc_name = request.POST.get('doc_name')

        if doc_name:

            # if create_method == DocCreateMethodEnum.PROJECT_ID.value:
            #     已不受支持

            if create_method == DocCreateMethodEnum.FOLDER_ID.value:
                # 获得所属文件夹下所有文档以验证重名
                ret = get_filecontainer_alldocs(folder_id)
                if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                    return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
                elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                    return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
                ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
                container_file = ret_data["container_file"]
                all_doc = ret_data["all_doc"]

                # warning: 验证没有使用file工具类

                try:
                    team = Teams.objects.get(team_id=container_file.team_id)
                except Teams.DoesNotExist:
                    return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
                try:
                    teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=container_file.team_id)
                except Teams2Users.DoesNotExist:
                    return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

                # 以list保存所有文档名称
                doc_name_list = []
                for doc_item in all_doc:
                    doc_name_list.append(doc_item.doc_name)

                try:
                    doc_name = generate_newname_norepeat(doc_name, doc_name_list, "新建")
                except Exception as e:
                    print(e)
                    return JsonResponse({"errno": 2002, "msg": "未知错误"})
                doc = Documents.objects.create(doc_name=doc_name,
                                               file_id=None,
                                               doc_status=DocStatusEnum.NORMAL.value,
                                               create_time=django.utils.timezone.now(),
                                               update_time=django.utils.timezone.now())
                # 创建一个文档的file model
                file = Files.objects.create(parent_id=container_file.file_id,
                                            folder_name=None,
                                            file_type=FileTypeEnum.DOCUMENT.value,
                                            content_id=doc.doc_id,
                                            team_id=container_file.team_id)

                doc.file_id = file.file_id
                doc.save()

                return JsonResponse({"errno": 0, "msg": "创建成功", "data": {
                    "doc_id": doc.doc_id,
                    "doc_token": create_file_token(str(doc.doc_id))}})
            pass

        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def move_file(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        # 获取请求参数
        file_id = request.POST.get("file_id")
        target_dirid = request.POST.get("target_dirid")
        if not file_id or not target_dirid:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})

        ret = check_existsfile_valid(file_id, target_dirid)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)

        container_file = ret_data["file_to_create_in"]
        target_file = ret_data["file"]

        if container_file.team_id != target_file.team_id and target_file.file_type != FileTypeEnum.DOCUMENT.value:
            return JsonResponse({"errno": 2009, "msg": "不应跨团队移动文件目录"})

        ret = check_file_privelige(container_file, user_id, allowRecycle=False)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

        ret = check_file_privelige(target_file, user_id, allowRecycle=False)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        target_file_content = ret_data["file_content"]

        ret = get_container_data(container_file)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        all_files = ret_data["data"]

        file_name_list = []
        for file_fm in all_files:
            if file_fm["file_type"] != target_file.file_type:
                continue
            file_name_list.append(get_file_namestr_fromformat(file_fm))
        target_file_name = get_file_namestr_fromfile(target_file, target_file_content)
        try:
            file_new_name = generate_newname_norepeat(target_file_name, file_name_list, "")
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 2002, "msg": "未知错误"})

        set_file_namestr_fromfile(target_file, target_file_content, file_new_name)

        target_file.parent_id = container_file.file_id
        target_file.team_id = container_file.team_id
        target_file.save()
        return JsonResponse({"errno": 0, "msg": "移动成功"})

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def get_file_parentid(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        # 获取请求参数
        file_id = request.POST.get("file_id")

        if not file_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})

        ret = check_file_privelige(file_id, user_id, allowRecycle=True)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        file = ret_data["file"]
        return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"parent_id": file.parent_id}})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def rename_folder(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        # 获取请求参数
        file_id = request.POST.get("file_id")
        folder_name = request.POST.get("folder_name")

        if not file_id or not folder_name:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})

        ret = check_file_privelige(file_id, user_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        file = ret_data["file"]
        if file.file_type != FileTypeEnum.FOLDER.value:
            return JsonResponse({"errno": 2003, "msg": "该文件不是文件夹"})

        if file.folder_name == folder_name:
            return JsonResponse({"errno": 0, "msg": "重命名成功"})
        # 检查文件夹名是否重复
        file_name_list = []
        ret = get_container_data(file.parent_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        all_files = ret_data["data"]

        file_name_list = []
        for file_fm in all_files:
            if file_fm["file_type"] != file.file_type:
                continue
            file_name_list.append(get_file_namestr_fromformat(file_fm))
        try:
            file_new_name = generate_newname_norepeat(folder_name, file_name_list, "")
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 2002, "msg": "未知错误"})

        file.folder_name = file_new_name
        file.save()
        return JsonResponse({"errno": 0, "msg": "重命名成功"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def get_team_root_fileid(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        # 获得团队id
        team_id = request.POST.get("team_id")
        if not team_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})

        ret = get_teamroot_file(team_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        teamroot_file = get_fileret_content(ret, FileretContentEnum.DATA)
        return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"file_id": teamroot_file.file_id}})

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def get_file_content(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        # 获得文件夹id
        file_id = request.POST.get("file_id")
        allow_recycle = request.POST.get("allow_recycle")
        if not file_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
        if allow_recycle:
            allow_recycle = True
        else:
            allow_recycle = False

        # 权限验证
        ret = check_file_privelige(file_id, user_id, allowRecycle=allow_recycle)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        retdata = get_fileret_content(ret, FileretContentEnum.DATA)

        # 获得文件内容
        ret = get_container_data(file_id, allowRecycle=allow_recycle)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        retdata = get_fileret_content(ret, FileretContentEnum.DATA)
        data = retdata["data"]
        return JsonResponse({"errno": 0, "msg": "获取成功", "data": data})


# TODO 待弃用
@csrf_exempt
def get_doc_list(request):
    # 获取文档列表
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        project_id = request.POST.get('project_id')
        if project_id:
            # 验证用户是否是该项目的所属的团队的成员
            try:
                project = Projects.objects.get(project_id=project_id)
            except Projects.DoesNotExist:
                return JsonResponse({"errno": 2005, "msg": "项目不存在"})
            if project.project_status != ProjectStatusEnum.NORMAL.value:
                return JsonResponse({"errno": 2006, "msg": "项目已被删除"})
            try:
                team = Teams.objects.get(team_id=project.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=project.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

            try:
                # 获得项目对应文件
                try:
                    project_file = Files.objects.get(content_id=project_id, file_type=FileTypeEnum.PROJECT.value)
                except Files.DoesNotExist:
                    return JsonResponse({"errno": 2003, "msg": "未知错误：项目文件夹不存在"})
                except Files.MultipleObjectsReturned:
                    return JsonResponse({"errno": 2004, "msg": "未知错误：项目文件夹不唯一"})

                ret = get_container_data(project_file.file_id, allowRecycle=True)
                if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                    return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
                elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                    return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

                ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
                all_doc_file = ret_data["data"]

                doc_normal_list = []
                doc_recycle_list = []
                for doc_fm in all_doc_file:
                    if doc_fm["file_type"] != FileTypeEnum.DOCUMENT.value:
                        continue
                    if doc_fm["detail"]["doc_status"] == DocStatusEnum.NORMAL.value:
                        doc_normal_list.append(doc_fm["detail"])
                    elif doc_fm["detail"]["doc_status"] == DocStatusEnum.RECYCLE.value:
                        doc_recycle_list.append(doc_fm["detail"])

                return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"doc_normal_list": doc_normal_list,
                                                                         "doc_recycle_list": doc_recycle_list}})
            except Exception as e:
                print(e)
                return JsonResponse({"errno": 2003, "msg": "未知错误"})

        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


def __copy_doc_by_docid__(doc_id, container_id, user_id):
    if not container_id:
        container_id = None

    if doc_id:
        # 验证用户对文档的权限

        target_folder_file = None
        ret = checkdoc_privelige(user_id, doc_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        doc_file = ret_data['file']
        doc = ret_data['doc']

        if container_id:
            ret = check_file_privelige(container_id, user_id)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
            target_folder_file = ret_data['file']
        else:

            # 获取文档所属的文件夹
            ret = get_parent_file(doc_file)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            target_folder_file = get_fileret_content(ret, FileretContentEnum.DATA)

        ret = check_doc_create_valid(target_folder_file)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        # target_folder_file = get_fileret_content(ret, FileretContentEnum.DATA)

        ret = get_container_data(target_folder_file, allowRecycle=False)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        all_doc_file = ret_data["data"]
        doc_name_list = []
        for doc_fm in all_doc_file:
            if doc_fm["file_type"] != FileTypeEnum.DOCUMENT.value:
                continue

            doc_name_list.append(doc_fm["detail"]["doc_name"])
        try:
            doc_new_name = generate_newname_norepeat(doc.doc_name, doc_name_list, "副本")
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 2002, "msg": "未知错误"})

        new_doc = Documents.objects.create(doc_name=doc_new_name,
                                           file_id=None,
                                           doc_status=DocStatusEnum.NORMAL.value,
                                           create_time=django.utils.timezone.now(),
                                           update_time=django.utils.timezone.now())
        # 创建一个文档的file model
        file = Files.objects.create(parent_id=target_folder_file.file_id,
                                    folder_name=None,
                                    file_type=FileTypeEnum.DOCUMENT.value,
                                    content_id=new_doc.doc_id,
                                    team_id=target_folder_file.team_id)

        new_doc.file_id = file.file_id
        new_doc.save()

        return JsonResponse({"errno": 0, "msg": "复制成功", "data": {
            "doc_id": doc.doc_id,
            "doc_token": create_file_token(str(doc.doc_id)),
            "new_doc_id": new_doc.doc_id,
            "new_doc_token": create_file_token(str(new_doc.doc_id))
        }})

    else:
        return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})


def __copy_doc_by_file__(file, file_content, container, retlist: list):
    """无条件将doc复制到container下"""

    new_doc = Documents.objects.create(doc_name=file_content.doc_name,
                                       file_id=None,
                                       doc_status=DocStatusEnum.NORMAL.value,
                                       create_time=django.utils.timezone.now(),
                                       update_time=django.utils.timezone.now())
    # 创建一个文档的file model
    file = Files.objects.create(parent_id=container.file_id,
                                folder_name=None,
                                file_type=FileTypeEnum.DOCUMENT.value,
                                content_id=new_doc.doc_id,
                                team_id=container.team_id)

    new_doc.file_id = file.file_id
    new_doc.save()

    retlist.append({
        "doc_id": file_content.doc_id,
        "doc_token": create_file_token(str(file_content.doc_id)),
        "new_doc_id": new_doc.doc_id,
        "new_doc_token": create_file_token(str(new_doc.doc_id))
    })
    pass


def __copy_folder_by_file__(file, container, retlist: list, new_name: str = None):
    # 创建文件夹
    if new_name is None:
        new_folder_name = file.folder_name
    else:
        new_folder_name = new_name

    new_folder = Files.objects.create(
        parent_id=container.file_id,
        folder_name=new_folder_name,
        file_type=FileTypeEnum.FOLDER.value,
        content_id=None,
        team_id=container.team_id,
        folder_status=FolderStatusEnum.NORMAL.value,
    )

    ret = get_container_data(file, allowRecycle=False)
    if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
    all_files_incontainer = ret_data["all_files_incontainer"]
    for fileitem in all_files_incontainer:
        if fileitem.file_type == FileTypeEnum.FOLDER.value:
            __copy_folder_by_file__(fileitem, new_folder, retlist)
        elif fileitem.file_type == FileTypeEnum.DOCUMENT.value:
            ret = checkfile_status(fileitem)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            file_content = get_fileret_content(ret, FileretContentEnum.DATA)
            __copy_doc_by_file__(fileitem, file_content, new_folder, retlist)
        else:
            raise Exception("未知的文件类型")


def __get_all_recycle_files__(containerfile: Files, namelist: list, retlist: list):
    """获取所有回收站文件"""
    # 入栈

    ret = checkfile_status(containerfile)

    if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))

    file_content = get_fileret_content(ret, FileretContentEnum.DATA)
    namestr = get_file_namestr_fromfile(containerfile, file_content)
    if namestr is not None:
        namelist.append(namestr)
    path_suffix = "/" + "/".join(namelist) + "/"
    # 获得所有文件
    ret = get_container_data(containerfile, allowRecycle=True)
    if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
    all_files_recycle = ret_data["all_files_incontainer"]

    ret = get_container_data(containerfile, allowRecycle=False)
    if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
    ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
    all_files_normal = ret_data["all_files_incontainer"]
    # 获得normal文件列表
    normalidlist = []

    for all_files_normal_file in all_files_normal:
        normalidlist.append(all_files_normal_file.file_id)
        if all_files_normal_file.file_type == FileTypeEnum.FOLDER.value:
            __get_all_recycle_files__(all_files_normal_file, namelist, retlist)
        elif all_files_normal_file.file_type == FileTypeEnum.PROJECT.value:
            if all_files_normal_file.file_id == 88:
                print("")
            __get_all_recycle_files__(all_files_normal_file, namelist, retlist)
        else:
            continue
    # 获得recycle文件列表
    for all_files_recycle_file in all_files_recycle:
        if all_files_recycle_file.file_id not in normalidlist:
            ret = get_content_data(all_files_recycle_file, allowRecycle=True)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            data = get_fileret_content(ret, FileretContentEnum.DATA)
            data["file_path"] = path_suffix
            retlist.append(data)

        continue

    # 出栈
    if namestr is not None:
        namelist.pop()
    pass


@csrf_exempt
def get_all_recycle_files(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        file_id = request.POST.get('file_id')
        if not file_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
        ret = check_file_privelige(file_id, user_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        container_file = ret_data["file"]
        name_list = []
        retlist = []
        try:
            __get_all_recycle_files__(container_file, name_list, retlist)
        except Exception as e:
            print(e)
            # print_exc()
            return JsonResponse({"errno": 1100, "msg": "获取回收站文件失败"})

        return JsonResponse({"errno": 0, "msg": "获取成功", "data": retlist})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方法错误"})


@csrf_exempt
def copy_project(request):
    """复制项目"""
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        project_id = request.POST.get('project_id')
        new_project_name = request.POST.get('new_project_name')
        if not project_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
        # 获取项目
        try:
            project = Projects.objects.get(project_id=project_id)
        except Projects.DoesNotExist:
            return JsonResponse({"errno": 2008, "msg": "项目不存在"})
        except Projects.MultipleObjectsReturned:
            return JsonResponse({"errno": 2009, "msg": "未知错误：多个同id项目"})
        # 获取项目的文件夹
        try:
            project_folder = Files.objects.get(content_id=project.project_id,
                                               file_type=FileTypeEnum.PROJECT.value, team_id=project.team_id)
        except Files.DoesNotExist:
            return JsonResponse({"errno": 2010, "msg": "找不到项目文件夹"})
        except Files.MultipleObjectsReturned:
            return JsonResponse({"errno": 2011, "msg": "未知错误：多个同id项目文件夹"})
        if not new_project_name:
            new_project_name = project.project_name + " 副本"
        # 验证权限
        ret = check_file_privelige(project_folder, user_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret = get_fileret_content(ret, FileretContentEnum.DATA)
        target_folder_file = ret["file"]
        # 复制项目
        try:
            teamroot = Files.objects.get(team_id=project_folder.team_id, file_type=FileTypeEnum.TEAM_ROOT.value)
        except Files.DoesNotExist:
            return JsonResponse({"errno": 2012, "msg": "未知错误：找不到团队根目录"})
        except Files.MultipleObjectsReturned:
            return JsonResponse({"errno": 2013, "msg": "未知错误：多个同id团队根目录"})
        # 创建新项目的载体
        new_project = Projects.objects.create(project_name=new_project_name,
                                              team_id=target_folder_file.team_id,
                                              project_status=ProjectStatusEnum.NORMAL.value,
                                              create_time=django.utils.timezone.now(),
                                              update_time=django.utils.timezone.now(),
                                              )
        # 新建文件model

        new_project_file = Files(parent_id=teamroot.file_id,
                                 folder_name=None,
                                 file_type=FileTypeEnum.PROJECT.value,
                                 content_id=new_project.project_id,
                                 team_id=project_folder.team_id,
                                 )
        new_project_file.save()
        # 复制项目下图的内容
        copy_graph_status = copy_project_graphs(old_project_id=project.project_id,
                                                new_project_id=new_project.project_id)
        if copy_graph_status:
            new_project.project_status = ProjectStatusEnum.DELETE.value
            new_project.save()
            # return JsonResponse({"errno": 1100, "msg": "复制图中途出错", "data": []})
            return JsonResponse({"errno": 1100, "msg": "复制图中途出错"})

        # 复制项目文件夹下内容
        retlist = []
        ret = get_container_data(project_folder, allowRecycle=False)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        all_files_incontainer = ret_data["all_files_incontainer"]
        try:
            for file in all_files_incontainer:
                if file.file_type == FileTypeEnum.FOLDER.value:
                    __copy_folder_by_file__(file, new_project_file, retlist)
                elif file.file_type == FileTypeEnum.DOCUMENT.value:
                    ret = checkfile_status(file)
                    if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
                    elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                        raise Exception(get_fileret_content(ret, FileretContentEnum.ERRINFO))
                    file_content = get_fileret_content(ret, FileretContentEnum.DATA)
                    __copy_doc_by_file__(file, file_content, new_project_file, retlist)
                else:
                    raise Exception("未知的文件类型")
        except Exception as e:
            new_project.project_status = ProjectStatusEnum.DELETE.value
            new_project.save()
            # return JsonResponse({"errno": 1100, "msg": "复制文档中途出错", "data": retlist})
            return JsonResponse({"errno": 1100, "msg": "复制文档中途出错"})
        return JsonResponse({"errno": 0, "msg": "复制成功", "data": retlist})
    else:
        return JsonResponse({"errno": 2002, "msg": "请求方法错误"})


@csrf_exempt
def del_folder(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        folder_id = request.POST.get('folder_id')
        # 文件权限检验
        ret = check_file_privelige(folder_id, user_id, allowRecycle=True)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        folder_file = ret_data["file"]
        # 类型检验
        if folder_file.file_type != FileTypeEnum.FOLDER.value:
            return JsonResponse({"errno": 2002, "msg": "文件类型错误"})

        if folder_file.folder_status == FolderStatusEnum.NORMAL.value:
            folder_file.folder_status = FolderStatusEnum.RECYCLE.value
            folder_file.save()
            return JsonResponse({"errno": 0, "msg": "删除成功"})
        elif folder_file.folder_status == FolderStatusEnum.RECYCLE.value:
            return JsonResponse({"errno": 2004, "msg": "文件已经在回收站"})
        elif folder_file.folder_status == FolderStatusEnum.DELETE.value:
            return JsonResponse({"errno": 2005, "msg": "文件已删除"})
        else:
            return JsonResponse({"errno": 2006, "msg": "文件状态错误"})

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方法错误"})


@csrf_exempt
def recycle_folder(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        folder_id = request.POST.get('folder_id')
        # 文件权限检验
        ret = check_file_privelige(folder_id, user_id, allowRecycle=True)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        folder_file = ret_data["file"]
        # 类型检验
        if folder_file.file_type != FileTypeEnum.FOLDER.value:
            return JsonResponse({"errno": 2002, "msg": "文件类型错误"})

        if folder_file.folder_status == FolderStatusEnum.NORMAL.value:
            return JsonResponse({"errno": 2004, "msg": "文件已经恢复"})
        elif folder_file.folder_status == FolderStatusEnum.RECYCLE.value:
            folder_file.folder_status = FolderStatusEnum.NORMAL.value
            folder_file.save()
            return JsonResponse({"errno": 0, "msg": "恢复成功"})
        elif folder_file.folder_status == FolderStatusEnum.DELETE.value:
            return JsonResponse({"errno": 2005, "msg": "文件已删除"})
        else:
            return JsonResponse({"errno": 2006, "msg": "文件状态错误"})

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方法错误"})


@csrf_exempt
def permanent_del_folder(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        folder_id = request.POST.get('folder_id')
        if not folder_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
        # 文件权限检验
        ret = check_file_privelige(folder_id, user_id, allowRecycle=True)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        folder_file = ret_data["file"]
        # 类型检验
        if folder_file.file_type != FileTypeEnum.FOLDER.value:
            return JsonResponse({"errno": 2002, "msg": "文件类型错误"})

        if folder_file.folder_status == FolderStatusEnum.NORMAL.value:
            return JsonResponse({"errno": 2004, "msg": "文件不在回收站"})
        elif folder_file.folder_status == FolderStatusEnum.RECYCLE.value:
            folder_file.folder_status = FolderStatusEnum.DELETE.value
            folder_file.save()
            return JsonResponse({"errno": 0, "msg": "删除成功"})
        elif folder_file.folder_status == FolderStatusEnum.DELETE.value:
            return JsonResponse({"errno": 2005, "msg": "文件已删除"})
        else:
            return JsonResponse({"errno": 2006, "msg": "文件状态错误"})

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方法错误"})


@csrf_exempt
def copy_folderfile(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        folder_id = request.POST.get('folder_id')
        target_dirid = request.POST.get('target_dirid')
        new_folder_name = request.POST.get('new_folder_name')
        if not folder_id:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})

        # 文件权限检验1
        ret = check_file_privelige(folder_id, user_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        folder_file = ret_data["file"]

        if not target_dirid:
            target_dirid = folder_file.parent_id

        # 创建合法性检验
        ret = check_folder_create_valid(target_dirid)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        target_dir_file = get_fileret_content(ret, FileretContentEnum.DATA)

        # 文件权限检验2
        ret = check_file_privelige(target_dir_file, user_id)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

        # 类型检验
        if folder_file.file_type != FileTypeEnum.FOLDER.value:
            return JsonResponse({"errno": 2004, "msg": "尝试复制的文件不是文件夹"})
        # 子文件夹检验
        ret = check_is_ancestors(folder_file, target_dir_file)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        if ret_data["is_ancestors"] == True:
            return JsonResponse({"errno": 2005, "msg": "不能将文件夹复制到自己的子文件夹中"})

        # 文件名检验
        if not new_folder_name:
            new_folder_name = folder_file.folder_name

        # 获得全部文件夹验证重名
        ret = get_container_data(target_dir_file, allowRecycle=False)
        if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
            return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
        ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
        all_doc_file = ret_data["data"]
        folder_name_list = []
        for folder_fm in all_doc_file:
            if folder_fm["file_type"] != FileTypeEnum.FOLDER.value:
                continue

            folder_name_list.append(folder_fm["folder_name"])
        try:
            new_folder_name = generate_newname_norepeat(new_folder_name, folder_name_list, "副本")
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 2002, "msg": "未知错误"})

        # 复制文件夹
        retlist = []
        try:
            __copy_folder_by_file__(folder_file, target_dir_file, retlist, new_folder_name)
        except Exception as e:
            print(e)
            return JsonResponse({"errno": 1100, "msg": "复制文件夹中途出错"})
            # return JsonResponse({"errno": 1100, "msg": "复制文件夹中途出错", "data": retlist})
        return JsonResponse({"errno": 0, "msg": "复制成功", "data": retlist})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方法错误"})


def __copy_doc_list__(request_data_list, user_id):
    outcome_list = []
    if request_data_list:
        for request_data in request_data_list:
            doc_id = request_data.get("doc_id")
            folder_id = request_data.get("folder_id")
            ret = __copy_doc_by_docid__(doc_id, folder_id, user_id)
            outcome_list.append(ret)
        return JsonResponse({"errno": 0, "msg": "复制成功", "data": outcome_list})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})


@csrf_exempt
def copy_doc_list(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        request_data_list = json.loads(request.body)
        return __copy_doc_list__(request_data_list, user_id)


    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def copy_doc(request):
    # 创建一个文档的副本
    # 其名称为原文档名称加上“副本” 重名则在名称后加上不重复的最高数字
    # 其除了doc_id、doc_name字段外其余均与原文档相同
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        doc_id = request.POST.get('doc_id')
        folder_id = request.POST.get('folder_id')
        return __copy_doc_by_docid__(doc_id, folder_id, user_id)

    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def create_folder(request):
    if request.method == "POST":
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        target_folder_id = request.POST.get('folder_id')
        new_folder_name = request.POST.get('new_folder_name')
        if target_folder_id and new_folder_name:
            # 获得顶层文件夹的file model
            ret = check_folder_create_valid(target_folder_id)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            target_folder_file = get_fileret_content(ret, FileretContentEnum.DATA)
            # 验证访问权限
            ret = check_file_privelige(target_folder_file, user_id)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

            # 获得全部文件夹验证重名

            ret = get_container_data(target_folder_file, allowRecycle=False)
            if get_fileret_content(ret, FileretContentEnum.ISSUCESS) == False:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))
            elif get_fileret_content(ret, FileretContentEnum.DATA) == None:
                return JsonResponse(get_fileret_content(ret, FileretContentEnum.ERRINFO))

            ret_data = get_fileret_content(ret, FileretContentEnum.DATA)
            all_doc_file = ret_data["data"]
            folder_name_list = []
            for folder_fm in all_doc_file:
                if folder_fm["file_type"] != FileTypeEnum.FOLDER.value:
                    continue

                folder_name_list.append(folder_fm["folder_name"])
            try:
                new_folder_name = generate_newname_norepeat(new_folder_name, folder_name_list, "新建")
            except Exception as e:
                print(e)
                return JsonResponse({"errno": 2002, "msg": "未知错误"})

            # 创建文件夹
            new_folder = Files.objects.create(
                parent_id=target_folder_file.file_id,
                folder_name=new_folder_name,
                file_type=FileTypeEnum.FOLDER.value,
                content_id=None,
                team_id=target_folder_file.team_id,
                folder_status=FolderStatusEnum.NORMAL.value,
            )
            return JsonResponse({"errno": 0, "msg": "创建成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


# def copy_docs_in_project(request):
#     # 创建一个项目下的所有文档的副本
#     # 其名称为原文档名称加上“副本” 重名则在名称后加上不重复的最高数字
#     # 其除了doc_id、doc_name字段外其余均与原文档相同
#     if request.method == 'POST':
#         payload = getTokenPayloadOfRequest(request)
#         if payload is None:
#             return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
#         user_id = payload['payload']
#         # 验证用户是否激活
#         user = Users.objects.get(user_id=user_id)
#         if user.user_status == UserStatusEnum.INACTIVE.value:
#             return JsonResponse({"errno": 1001, "msg": "用户未激活"})
#         project_id = request.POST.get('project_id')
#         if project_id:
#             # 验证用户是否是该文档所属的项目的所属的团队的成员
#             try:
#                 project = Projects.objects.get(project_id=project_id)
#             except Projects.DoesNotExist:
#                 return JsonResponse({"errno": 2005, "msg": "项目不存在"})
#             if project.project_status != ProjectStatusEnum.NORMAL.value:
#                 return JsonResponse({"errno": 2006, "msg": "项目已被删除"})
#             try:
#                 team = Teams.objects.get(team_id=project.team_id)
#             except Teams.DoesNotExist:
#                 return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
#             try:
#                 teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=project.team_id)
#             except Teams2Users.DoesNotExist:
#                 return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})


@csrf_exempt
def del_doc(request):
    # 删除文档
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})

        file_id = request.POST.get('file_id')
        if file_id:
            # 获取文件
            try:
                file = Files.objects.get(file_id=file_id)
            except Files.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档文件不存在"})
            # 获取文档
            try:
                doc = Documents.objects.get(doc_id=file.content_id)
            except Documents.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档不存在"})

            try:
                team = Teams.objects.get(team_id=file.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=file.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})
            try:
                if doc.doc_status == DocStatusEnum.NORMAL.value:
                    doc.doc_status = DocStatusEnum.RECYCLE.value
                    doc.save()
                    return JsonResponse({"errno": 0, "msg": "删除成功"})
                elif doc.doc_status == DocStatusEnum.RECYCLE.value:
                    return JsonResponse({"errno": 2011, "msg": "文档已在回收站"})
                else:
                    return JsonResponse({"errno": 2012, "msg": "未知错误:项目状态错误"})
            except Exception as e:
                print(e)
                return JsonResponse({"errno": 2003, "msg": "未知错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def permanent_del_doc(request):
    # 永久删除文档
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        file_id = request.POST.get('file_id')
        if file_id:
            # 获取文件
            try:
                file = Files.objects.get(file_id=file_id)
            except Files.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档文件不存在"})
            # 获取文档
            try:
                doc = Documents.objects.get(doc_id=file.content_id)
            except Documents.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档不存在"})

            try:
                team = Teams.objects.get(team_id=file.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=file.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

            if doc.doc_status == DocStatusEnum.RECYCLE.value:
                doc.doc_status = DocStatusEnum.DELETE.value
                doc.save()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            elif doc.doc_status == DocStatusEnum.NORMAL.value:
                return JsonResponse({"errno": 2011, "msg": "文档不在回收站"})
            elif doc.doc_status == DocStatusEnum.DELETE.value:
                return JsonResponse({"errno": 2012, "msg": "文档已被删除"})
            else:
                return JsonResponse({"errno": 2013, "msg": "未知错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def recycle_doc(request):
    # 回收文档
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        file_id = request.POST.get('file_id')
        if file_id:
            # 获取文件
            try:
                file = Files.objects.get(file_id=file_id)
            except Files.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档文件不存在"})
            # 获取文档
            try:
                doc = Documents.objects.get(doc_id=file.content_id)
            except Documents.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档不存在"})

            try:
                team = Teams.objects.get(team_id=file.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=file.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

            if doc.doc_status == DocStatusEnum.RECYCLE.value:
                doc.doc_status = DocStatusEnum.NORMAL.value
                doc.save()
                return JsonResponse({"errno": 0, "msg": "回收成功"})
            elif doc.doc_status == DocStatusEnum.NORMAL.value:
                return JsonResponse({"errno": 2011, "msg": "文档不在回收站"})
            elif doc.doc_status == DocStatusEnum.DELETE.value:
                return JsonResponse({"errno": 2012, "msg": "文档已被删除"})
            else:
                return JsonResponse({"errno": 2013, "msg": "未知错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def rename_doc(request):
    # 重命名文档
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        file_id = request.POST.get('file_id')
        doc_name = request.POST.get('doc_name')
        if file_id and doc_name:
            # 获取文件
            try:
                file = Files.objects.get(file_id=file_id)
            except Files.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档文件不存在"})
            # 获取文档
            try:
                doc = Documents.objects.get(doc_id=file.content_id)
            except Documents.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "文档不存在"})

            try:
                team = Teams.objects.get(team_id=file.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2009, "msg": "未知错误：项目所属团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=file.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2010, "msg": "您不是该团队成员"})

            if doc.doc_status == DocStatusEnum.NORMAL.value:
                doc.doc_name = doc_name
                doc.save()
                return JsonResponse({"errno": 0, "msg": "文档重命名成功"})
            elif doc.doc_status == DocStatusEnum.RECYCLE.value:
                return JsonResponse({"errno": 2011, "msg": "文档已删除"})
            else:
                return JsonResponse({"errno": 2012, "msg": "未知错误：文档状态错误"})

        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def new_graph(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_type = request.POST.get('graph_type')
        template = request.POST.get('template')
        project_id = request.POST.get('project_id')

        if graph_type and template:
            graph_name = '未命名 ' + str(django.utils.timezone.now()) + " " + user.user_name,
            graph = Graphs(graph_name=graph_name, project_id=project_id,
                           graph_status=GraphStatusEnum.NORMAL.value,
                           create_time=django.utils.timezone.now(), update_time=django.utils.timezone.now(),
                           graph_data=GraphTemplate.templates[int(template)], graph_type=graph_type)
            graph.save()
            return JsonResponse({"errno": 0, "msg": "创建成功", "data": {"graph_id": graph.graph_id}})

        else:
            return JsonResponse({"errno": 2006, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def del_graph(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')
        if graph_id:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "图不存在"})

            if graph.graph_status == GraphStatusEnum.NORMAL.value:
                graph.graph_status = GraphStatusEnum.RECYCLE.value
                graph.update_time = django.utils.timezone.now()
                graph.save()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            elif graph.graph_status == GraphStatusEnum.RECYCLE.value:
                return JsonResponse({"errno": 2005, "msg": "图已加入回收站"})
            else:
                return JsonResponse({"errno": 2006, "msg": "未知错误：图状态错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def modify_graph(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')
        graph_name = request.POST.get('graph_name')
        graph_info = request.POST.get('graph_info')
        if graph_id and graph_name and graph_info:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "图不存在"})

            graph.graph_name = graph_name
            graph.graph_info = graph_info
            graph.update_time = django.utils.timezone.now()
            graph.save()
            return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_graph_data(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')
        graph_data = request.POST.get('graph_data')
        # print(graph_data)
        if graph_id:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "图不存在"})

            graph.graph_data = graph_data
            # print(graph.data)
            graph.update_time = django.utils.timezone.now()
            graph.save()
            # print(graph.data)
            return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def get_user_projects(request):
    if request.method == 'GET':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        allprojectlist = []
        try:
            teams = Teams2Users.objects.filter(user_id=user_id)
        except Teams2Users.DoesNotExist:
            return JsonResponse({"errno": 2003, "msg": "用户未在团队中"})
        for team in teams:
            team_id = team.team_id
            projectlist = Projects.objects.filter(team_id=team_id)
            for project in projectlist:
                allprojectlist.append(project)
        project_normal_list = []
        project_recycle_list = []
        for project in allprojectlist:
            team = Teams.objects.get(team_id=project.team_id)
            if project.project_status == ProjectStatusEnum.NORMAL.value:

                project_normal_list.append({"project_id": project.project_id, "project_name": project.project_name,
                                            "create_time": project.create_time, "update_time": project.update_time,
                                            "project_status": project.project_status, "team_id": project.team_id,
                                            "team_name": team.team_name})
            elif project.project_status == ProjectStatusEnum.RECYCLE.value:
                project_recycle_list.append({"project_id": project.project_id, "project_name": project.project_name,
                                             "create_time": project.create_time, "update_time": project.update_time,
                                             "project_status": project.project_status, "team_id": project.team_id,
                                             "team_name": team.team_name})

        return JsonResponse({"errno": 0, "msg": "获取成功", "data": {"project_normal_list": project_normal_list,
                                                                 "project_recycle_list": project_recycle_list}})

    else:
        return JsonResponse({"errno": 2007, "msg": "请求方式错误"})


@csrf_exempt
def get_graph(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')
        if graph_id:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "图不存在"})

            return JsonResponse({"errno": 0, "msg": "修改成功", "data": {
                "header": graph.graph_name,
                "brief": graph.graph_info,
                "lastedit": graph.update_time,
                "data": graph.graph_data,
            }})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def recover_graph(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')
        if graph_id:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "图不存在"})

            if graph.graph_status == GraphStatusEnum.RECYCLE.value:
                graph.graph_status = GraphStatusEnum.NORMAL.value
                graph.update_time = django.utils.timezone.now()
                graph.save()
                return JsonResponse({"errno": 0, "msg": "恢复成功"})
            elif graph.graph_status == GraphStatusEnum.DELETE.value:
                return JsonResponse({"errno": 2005, "msg": "图已彻底删除"})
            else:
                return JsonResponse({"errno": 2006, "msg": "未知错误：图状态错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def get_graph_list(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        project_id = request.POST.get('project_id')
        graph_type = request.POST.get('type')
        graph_status = request.POST.get('isdeleted')
        try:
            graph_list = Graphs.objects.filter(project_id=int(project_id), graph_type=int(graph_type))
            # graph_list 按降序更新时间排列
            graph_list = graph_list.order_by('-update_time')

        except Graphs.DoesNotExist:
            graph_list = []
            pass
        data = {}
        graph_list_json = []
        for graph in graph_list:
            if graph.graph_status == int(graph_status):
                graph_list_json.append(
                    {"graph_id": graph.graph_id, "graph_name": graph.graph_name})
        data['graph_list'] = graph_list_json

        return JsonResponse({"errno": 0, "msg": "获取成功", "data": data})
    else:
        return JsonResponse({"errno": 2003, "msg": "请求方式错误"})


@csrf_exempt
def full_del_graph(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')
        if graph_id:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2004, "msg": "图不存在"})

            if graph.graph_status == GraphStatusEnum.RECYCLE.value:
                graph.graph_status = GraphStatusEnum.DELETE.value
                graph.update_time = django.utils.timezone.now()
                graph.save()
                return JsonResponse({"errno": 0, "msg": "删除成功"})
            elif graph.graph_status == GraphStatusEnum.NORMAL.value:
                return JsonResponse({"errno": 2005, "msg": "请先删除图"})
            else:
                return JsonResponse({"errno": 2006, "msg": "未知错误：图状态错误"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_user_info(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        user_info = request.POST.get('user_info')
        if user_info:
            user.user_info = user_info
            user.save()
            return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_team_info(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        team_id = request.POST.get('team_id')
        team_info = request.POST.get('team_info')
        if team_id and team_info:
            try:
                team = Teams.objects.get(team_id=team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})
            if teamtouser.identitys >= TeamIdentityEnum.OWNER.value:
                team.team_info = team_info
                team.save()
                return JsonResponse({"errno": 0, "msg": "修改成功"})
            else:
                return JsonResponse({"errno": 2004, "msg": "您不是该团队拥有者"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_password(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        pass_word = request.POST.get('pass_word')
        old_pass_word = request.POST.get('old_pass_word')
        if pass_word and old_pass_word:
            if old_pass_word != user.pass_word:
                return JsonResponse({"errno": 2002, "msg": "原始密码错误"})
            else:
                user.pass_word = pass_word
                user.save()
                return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_username(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        user_name = request.POST.get('user_name')
        if user_name:
            if Users.objects.filter(user_name=user_name):
                return JsonResponse({"errno": 2002, "msg": "用户名已存在"})
            else:
                user.user_name = user_name
                user.save()
                return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def update_user_realname(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        real_name = request.POST.get('real_name')
        if real_name:
            # 用户真实姓名 半年只可以改一次
            half_year = datetime.timedelta(weeks=26)  # 半年
            # 注意:user.real_name_update_time在数据库中必须不为null 否则'-'不能进行运算
            if django.utils.timezone.now() - user.real_name_update_time < half_year:
                return JsonResponse({"errno": 2002, "msg": "用户真实姓名半年内只能修改一次"})
            else:
                user.real_name = real_name
                user.real_name_update_time = django.utils.timezone.now()
                user.save()
            return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def generate_forget_link(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        if email:
            try:
                user = Users.objects.get(email=email)
            except Users.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "用户或邮箱不存在"})
            forget_payload = {"user_id": user.user_id}
            token = create_token(forget_payload, TokenTypeEnum.FORGET_TOKEN.value)
            forget_link = JumpLink.FORGET_URL.value + token
            send_status = send_verification_code(email, '1', forget_link, user_name=user.user_name)
            if send_status == EmailSendStatusEnum.FAIL.value:
                return JsonResponse({"errno": 2005, "msg": "邮件发送失败"})
            else:
                return JsonResponse({"errno": 0, "msg": "忘记密码链接生成成功", "data": {"forget_link": forget_link}})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def forget_by_token(request):
    if request.method == 'POST':
        token = request.POST.get('token')
        pass_word = request.POST.get('pass_word')
        # 验证token
        if not token and not pass_word:
            return JsonResponse({"errno": 2002, "msg": "请求参数存在空值"})
        else:
            pass
        # 解析token
        forget_payload = validate_token(token, TokenTypeEnum.FORGET_TOKEN.value)
        if forget_payload is None:
            return JsonResponse({"errno": 2003, "msg": "忘记密码链接错误"})
        forget_payload = forget_payload['payload']
        user_id = forget_payload['user_id']
        try:
            user = Users.objects.get(user_id=user_id)
        except Users.DoesNotExist:
            return JsonResponse({"errno": 2004, "msg": "用户不存在"})
        print(user_id)
        user.pass_word = pass_word
        user.save()
        return JsonResponse({"errno": 0, "msg": "修改成功"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def upload_profile(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        profile = request.POST.get('profile')
        if profile:
            user.profile = profile
            user.save()
            return JsonResponse({"errno": 0, "msg": "修改成功"})
        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def generate_graph_token(request):
    if request.method == 'POST':
        payload = getTokenPayloadOfRequest(request)
        if payload is None:
            return JsonResponse({"errno": 2001, "msg": "用户未登录或登录已过期"})
        user_id = payload['payload']
        # 验证用户是否激活
        user = Users.objects.get(user_id=user_id)
        if user.user_status == UserStatusEnum.INACTIVE.value:
            return JsonResponse({"errno": 1001, "msg": "用户未激活"})
        graph_id = request.POST.get('graph_id')

        if graph_id:
            try:
                graph = Graphs.objects.get(graph_id=graph_id)
            except Graphs.DoesNotExist:
                return JsonResponse({"errno": 2002, "msg": "图不存在"})
            try:
                project = Projects.objects.get(project_id=graph.project_id)
            except Projects.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "项目不存在"})
            try:
                team = Teams.objects.get(team_id=project.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "团队不存在"})
            try:
                team = Teams.objects.get(team_id=project.team_id)
            except Teams.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "团队不存在"})
            try:
                teamtouser = Teams2Users.objects.get(user_id=user_id, team_id=team.team_id)
            except Teams2Users.DoesNotExist:
                return JsonResponse({"errno": 2003, "msg": "您不是该团队成员"})

            graph_payload = {"graph_id": graph_id}
            token = create_token(graph_payload, TokenTypeEnum.GRAPH_TOKEN.value)
            graph_link = JumpLink.GRAPH_URL.value + token

            return JsonResponse({"errno": 0, "msg": "图token生成成功", "data": {"token": token, "graph_link": graph_link}})

        else:
            return JsonResponse({"errno": 2007, "msg": "请求参数存在空值"})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})


@csrf_exempt
def get_graph_by_token(request):
    if request.method == 'POST':
        token = request.POST.get('token')
        # 验证token
        if not token:
            return JsonResponse({"errno": 2002, "msg": "请求参数存在空值"})
        else:
            pass
        # 解析token
        graph_payload = validate_token(token, TokenTypeEnum.GRAPH_TOKEN.value)

        if graph_payload is None:
            return JsonResponse({"errno": 2003, "msg": "邀请链接错误"})

        graph_payload = graph_payload['payload']

        graph_id = graph_payload['graph_id']

        try:
            graph = Graphs.objects.get(graph_id=graph_id)
        except Graphs.DoesNotExist:
            return JsonResponse({"errno": 2004, "msg": "图不存在"})

        return JsonResponse(
            {"errno": 0, "msg": "返回成功",
             "data": {"graph_id": graph.graph_id,
                      "graph_name": graph.graph_name,
                      "graph_info": graph.graph_info,
                      "graph_data": graph.graph_data}})
    else:
        return JsonResponse({"errno": 2008, "msg": "请求方式错误"})
